package conf

import (
	tools "base/util/tools"
	"fmt"
	"github.com/creasty/defaults"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

//解析yml文件
type Config struct {
	Project    string `yaml:"Project"`
	Server     string `yaml:"Server"`
	Host       string `yaml:"Host"`
	Timeout    string `yaml:"Timeout" default:"10"`
	OutputFile string `yaml:"OutputFile"`
	Debug      bool   `yaml:"Debug"`
	Port       string `yaml:"Port"`
	Logs       Logs   `yaml:"Logs"`
	Tasks      []Task `yaml:"Tasks"`
}

type Task struct {
	Name string `yaml:"Name,omitempty"`
	Desc string `yaml:"Desc,omitempty"`
	Cron string `yaml:"Cron,omitempty"`
}

type Logs struct {
	Path         string `yaml:"Path"`
	Name         string `yaml:"Name"`
	Level        string `yaml:"Level"`
	LogMaxAge    int    `yaml:"LogMaxAge" default:"10"` // 日志最大保留时间
	RotationTime int    `yaml:"RotationTime"`
}

var Conf = &Config{}

func (c *Config) Unmarshal (y []byte) error {
	defaults.Set(c)
	if err := yaml.Unmarshal(y, Conf); err != nil {
		return err
	}
	return nil
}

func init() {
	abPath := tools.GetPwd()
	configFile := fmt.Sprintf("%s/conf.yml", abPath)
	yamlFile, err := ioutil.ReadFile(configFile)
	if err != nil {
		panic(err.Error())
	}
	err = Conf.Unmarshal(yamlFile)
	if err != nil {
		panic(err.Error())
	}
}
